import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:wy/utils/dialog_util.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: Page1(),
    );
  }
}

class Page1 extends HookWidget {
  var player;
  Page1({Key key}) : super(key: key) {
    player = AudioPlayer();
  }

  @override
  Widget build(BuildContext context) {
    final time = useState('00:00');
    player.onAudioPositionChanged.listen((duration) {
      var sec = duration.inSeconds;

      var m = (sec ~/ 60).toString().padLeft(2, '0');
      var s = (sec % 60).toString().padLeft(2, '0');

      time.value = '$m:$s';
    });
    player.onPlayerStateChanged.listen((event) {
      print('player state changed: $event');
    });
    player.onPlayerError.listen((event) {
      print('player error: $event');
      alert(context, title: '播放失败', msg: '音乐无法加载，请检查网络连接，然后重试');
      time.value = '错误';
    });

    const kUrl1 = 'https://luan.xyz/files/audio/ambient_c_motion.mp3';
    return Scaffold(
      appBar: AppBar(title: Text('播放器')),
      body: Center(
        child: Column(
          children: [
            Text('播放时间:${time.value}'),
            FlatButton(
              color: Colors.blue,
              onPressed: () async {
                var res = await player.play(kUrl1);
                if (res != 1) {
                  //资源都没生成
                  alert(context, title: '播放失败', msg: '音乐无法加载，请检查网络连接，然后重试');
                }
                // 这玩意的要是找不到资源读取时间挺长鸭-我艹
                time.value = '读取中...';
              },
              child: Text('播放'),
            ),
            FlatButton(
              color: Colors.blue,
              child: Text('停止'),
              onPressed: () async {
                var res = await player.stop();

                time.value = '00:00';

                if (res != 1) {
                  alert(context, title: '播放失败', msg: '音乐无法加载，请检查网络连接，然后重试');
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}
